package com.xcoder.leetcode;

import apple.laf.JRSUIUtils;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * https://leetcode-cn.com/problems/binary-tree-level-order-traversal/
 */
public class _102_二叉树的层序遍历 {

    /**
     * Definition for a binary tree node.
     */
    private class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            List<Integer> list = new ArrayList<>();
            for (int i = 0, size = queue.size(); i < size; i++) {
                TreeNode first = queue.poll();
                if (first != null) {
                    list.add(first.val);
                    if (first.left != null) {
                        queue.offer(first.left);
                    }
                    if (first.right != null) {
                        queue.offer(first.right);
                    }
                }
            }
            if (!list.isEmpty()) {
                result.add(list);
            }
        }
        return result;
    }

}
